<?php
function wptexturize($text) {
    global $wp_cockneyreplace;
    $next = true;
    $output = '';
    $curl = '';
    $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    $stop = count($textarr);

    // if a plugin has provided an autocorrect array, use it
    if ( isset($wp_cockneyreplace) ) {
        $cockney = array_keys($wp_cockneyreplace);
        $cockneyreplace = array_values($wp_cockneyreplace);
    } else {
        $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
        $cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
    }

    $static_characters = array_merge(array('---', ' -- ', '--', 'xn&#8211;', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
    $static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', 'xn--', '&#8230;', '&#8220;', '&#8217;s', '&#8221;', ' &#8482;'), $cockneyreplace);

    $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
    $dynamic_replacements = array('&#8217;$1','$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1&#8220;$2', '&#8221;$1', '&#8217;$1', '$1&#215;$2');

    for ( $i = 0; $i < $stop; $i++ ) {
         $curl = $textarr[$i];

        if (isset($curl{0}) && '<' != $curl{0} && '[' != $curl{0} && $next) { // If it's not a tag
            // static strings
            $curl = str_replace($static_characters, $static_replacements, $curl);
            // regular expressions
            $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
        } elseif (strpos($curl, '<code') !== false || strpos($curl, '<pre') !== false || strpos($curl, '<kbd') !== false || strpos($curl, '<style') !== false || strpos($curl, '<script') !== false) {
            $next = false;
        } else {
            $next = true;
        }

        $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
        $output .= $curl;
    }

      return $output;
}

function sanitize_file_name( $name ) { // Like sanitize_title, but with periods
    $name = strtolower( $name );
    $name = preg_replace('/&.+?;/', '', $name); // kill entities
    $name = str_replace( '_', '-', $name );
    $name = preg_replace('/[^a-z0-9\s-.]/', '', $name);
    $name = preg_replace('/\s+/', '-', $name);
    $name = preg_replace('|-+|', '-', $name);
    $name = trim($name, '-');
    return $name;
}

function sanitize_user( $username, $strict = false ) {
    $raw_username = $username;
    $username = strip_tags($username);
    // Kill octets
    $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
    $username = preg_replace('/&.+?;/', '', $username); // Kill entities

    // If strict, reduce to ASCII for max portability.
    if ( $strict )
        $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);

    return apply_filters('sanitize_user', $username, $raw_username, $strict);
}

function sanitize_title($title, $fallback_title = '') {
    $title = strip_tags($title);
    $title = apply_filters('sanitize_title', $title);

    if ( '' === $title || false === $title )
        $title = $fallback_title;

    return $title;
}

function clean_url( $url, $protocols = null, $context = 'display' ) {
    $original_url = $url;

    if ('' == $url) return $url;
    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@()]|i', '', $url);
    $strip = array('%0d', '%0a');
    $url = str_replace($strip, '', $url);
    $url = str_replace(';//', '://', $url);
    /* If the URL doesn't appear to contain a scheme, we
     * presume it needs http:// appended (unless a relative
     * link starting with / or a php file).
    */
    if ( strpos($url, ':') === false &&
        substr( $url, 0, 1 ) != '/' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
        $url = 'http://' . $url;

    // Replace ampersands ony when displaying.
    if ( 'display' == $context )
        $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&#038;$1', $url);

    if ( !is_array($protocols) )
        $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet');
    if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
        return '';

    return apply_filters('clean_url', $url, $original_url, $context);
}

function al_specialchars( $text, $quotes = 0 ) {
    // Like htmlspecialchars except don't double-encode HTML entities
    $text = str_replace('&&', '&#038;&', $text);
    $text = str_replace('&&', '&#038;&', $text);
    $text = preg_replace('/&(?:$|([^#])(?![a-z1-4]{1,8};))/', '&#038;$1', $text);
    $text = str_replace('<', '&lt;', $text);
    $text = str_replace('>', '&gt;', $text);
    if ( 'double' === $quotes ) {
        $text = str_replace('"', '&quot;', $text);
    } elseif ( 'single' === $quotes ) {
        $text = str_replace("'", '&#039;', $text);
    } elseif ( $quotes ) {
        $text = str_replace('"', '&quot;', $text);
        $text = str_replace("'", '&#039;', $text);
    }
    return $text;
}


// Escaping for HTML attributes
function attribute_escape($text) {
    $safe_text = al_specialchars($text, true);
    return apply_filters('attribute_escape', $safe_text, $text);
}

function convert_chars($content, $deprecated = '') {
    // Translation of invalid Unicode references range to valid range
    $wp_htmltranswinuni = array(
    '&#128;' => '&#8364;', // the Euro sign
    '&#129;' => '',
    '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
    '&#131;' => '&#402;',  // they would look weird on non-Windows browsers
    '&#132;' => '&#8222;',
    '&#133;' => '&#8230;',
    '&#134;' => '&#8224;',
    '&#135;' => '&#8225;',
    '&#136;' => '&#710;',
    '&#137;' => '&#8240;',
    '&#138;' => '&#352;',
    '&#139;' => '&#8249;',
    '&#140;' => '&#338;',
    '&#141;' => '',
    '&#142;' => '&#382;',
    '&#143;' => '',
    '&#144;' => '',
    '&#145;' => '&#8216;',
    '&#146;' => '&#8217;',
    '&#147;' => '&#8220;',
    '&#148;' => '&#8221;',
    '&#149;' => '&#8226;',
    '&#150;' => '&#8211;',
    '&#151;' => '&#8212;',
    '&#152;' => '&#732;',
    '&#153;' => '&#8482;',
    '&#154;' => '&#353;',
    '&#155;' => '&#8250;',
    '&#156;' => '&#339;',
    '&#157;' => '',
    '&#158;' => '',
    '&#159;' => '&#376;'
    );

    // Remove metadata tags
    $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
    $content = preg_replace('/<category>(.+?)<\/category>/','',$content);

    // Converts lone & characters into &#38; (a.k.a. &amp;)
    $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);

    // Fix Word pasting
    $content = strtr($content, $wp_htmltranswinuni);

    // Just a little XHTML help
    $content = str_replace('<br>', '<br />', $content);
    $content = str_replace('<hr>', '<hr />', $content);

    return $content;
}

function wpautop($pee, $br = 1) {
    $pee = $pee . "\n"; // just to make things a little easier, pad the end
    $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
    // Space things out a little
    $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)';
    $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
    $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
    $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
    if ( strpos($pee, '<object') !== false ) {
        $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
        $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
    }
    $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
    $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $pee); // make paragraphs, including one at the end
    $pee = preg_replace('|<p>\s*?</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
    $pee = preg_replace('!<p>([^<]+)\s*?(</(?:div|address|form)[^>]*>)!', "<p>$1</p>$2", $pee);
    $pee = preg_replace( '|<p>|', "$1<p>", $pee );
    $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
    $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
    $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
    $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
    $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
    $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
    if ($br) {
        $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
        $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
        $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
    }
    $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
    $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);

    $pee = preg_replace( "|\n</p>$|", '</p>', $pee );


    return $pee;
}
?>
